<?php

namespace oa\services;

use oa\models\User;
use Yii;
use oa\models\Contract;
use oa\models\ContractProduct;
use oa\models\ContractAttachment;
use common\components\Yuploader;

class ContractService extends BaseService
{

    public static function save($post, $id = 0)
    {
        if (empty($id)) {
            $model = new Contract();
            $model->scenario = Contract::SCENARIO_ADD;
        } else {
            $model = self::one($id);
            $model->scenario = Contract::SCENARIO_EDIT;
        }
        $data = [
            'pid'    => $post['pid'],
            'code'   => $post['code'],
            'uid'    => $post['uid'],
            'product_name' => $post['product_name'],
            'product_spec' => $post['product_spec'],
            'product_unit' => $post['product_unit'],
            'remark' => $post['remark'],
        ];
        if ($data['product_unit'] == '盒') {
            $data['amount_h'] = $post['product_amount'];
            $data['amount_x'] = round($post['product_amount'] / 30);
            $data['amount_b'] = $post['product_amount'] * 30;
        } elseif ($data['product_unit'] == '袋') {
            $data['amount_h'] = round($post['product_amount'] / 30);
            $data['amount_x'] = round($post['product_amount'] / 30 / 30);
            $data['amount_b'] = $post['product_amount'];
        } elseif ($data['product_unit'] == '箱') {
            $data['amount_h'] = $post['product_amount'];
            $data['amount_x'] = $post['product_amount'] * 30;
            $data['amount_b'] = $post['product_amount'] * 30 * 30;
        } else {
            $data['amount_h'] = 0;
            $data['amount_x'] = 0;
            $data['amount_b'] = 0;
        }

        if (!empty($post['start_over_at'])) {
            $start_over_at = explode(' - ', $post['start_over_at']);
            $data['start_at'] = strtotime($start_over_at[0]);
            $data['over_at'] = strtotime($start_over_at[1]);
        }

        if (!empty($post['total_fee'])) {
            $data['total_fee'] = $post['total_fee'] * 10000;
        }
        $res = $model->_save($data);
        if ($res !== true) {
            return $res;
        }
        $extra_products = [];
        if (!empty($post['product_extra_name'])) {
            foreach ($post['product_extra_name'] as $k=>$v) {
                $extra_products[] = [
                    'cid'        => $model->id,
                    'name'       => $v,
                    'brand'      => $post['product_extra_brand'][$k],
                    'spec'       => $post['product_extra_spec'][$k],
                    'unit'       => $post['product_extra_unit'][$k],
                    'remark'     => $post['product_extra_remark'][$k],
                    'aid'        => Yii::$app->user->id,
                    'updated_at' => time(),
                    'created_at' => time()
                ];
            }
            ContractProduct::insertAll($extra_products);
        }
        $attachments = [];
        if (!empty($post['attachment'])) {
            $uploader = new Yuploader();
            foreach ($post['attachment'] as $k=>$v) {
                $uploader->submit($v);
                $attachments[] = [
                    'cid'        => $model->id,
                    'name'       => $post['attachment_name'][$k],
                    'file_src'   => str_replace('/' . Yii::$app->params['upload']['tmp_path'], '', $v),
                    'aid'        => Yii::$app->user->id,
                    'updated_at' => time(),
                    'created_at' => time()
                ];
            }
            ContractAttachment::insertAll($attachments);
        }
        return true;
    }

	public static function getList()
    {
        $req= Yii::$app->request;
        $query = Contract::find();
        $query->alias('c');
        $query->select('c.*');
        $query->where('c.status<>-1');
        $query->andWhere(['c.status' => $req->get('status')]);
        $query->andFilterWhere(['c.code' => $req->get('code')]);
        $query->andFilterWhere(['>=', 'c.total_fee', $req->get('min_total_fee')]);
        $query->andFilterWhere(['<=', 'c.total_fee', $req->get('max_total_fee')]);
        $query->andFilterWhere(['>=', 'c.created_at', $req->get('min_created_at') ? strtotime($req->get('min_created_at')) : null]);
        $query->andFilterWhere(['<=', 'c.created_at', $req->get('max_created_at') ? strtotime($req->get('max_created_at')) : null]);
        $query->andFilterWhere(['>=', 'c.start_at', $req->get('min_start_at') ? strtotime($req->get('min_start_at')) : null]);
        $query->andFilterWhere(['<=', 'c.start_at', $req->get('max_start_at') ? strtotime($req->get('max_start_at')) : null]);
        $query->andFilterWhere(['>=', 'c.end_at', $req->get('min_end_at') ? strtotime($req->get('min_end_at')) : null]);
        $query->andFilterWhere(['<=', 'c.end_at', $req->get('max_end_at') ? strtotime($req->get('max_end_at')) : null]);
        $query->andFilterWhere(['>=', 'c.sign_at', $req->get('min_sign_at') ? strtotime($req->get('min_sign_at')) : null]);
        $query->andFilterWhere(['<=', 'c.sign_at', $req->get('max_sign_at') ? strtotime($req->get('max_sign_at')) : null]);
        $query->andFilterWhere(['c.s_uid' => $req->get('s_uid')]);
        $query->andFilterWhere(['c.province' => $req->get('province')]);
        $query->andFilterWhere(['c.city' => $req->get('city')]);
        $query->andFilterWhere(['c.county' => $req->get('county')]);
        $query->andFilterWhere(['like', 'c.unit', $req->get('unit')]);
        $countQuery = clone $query;
        $query->orderBy(['c.created_at' => SORT_DESC]);
        $rows = $query->offset($req->get('offset'))->limit($req->get('limit'))->asArray()->all();
        foreach ($rows as $k=>$v) {
            $rows[$k]['start_at'] = date('Y-m-d H:i', $v['start_at']);
            $rows[$k]['end_at'] = date('Y-m-d H:i', $v['end_at']);
            $rows[$k]['sign_at'] = date('Y-m-d H:i', $v['sign_at']);
            $rows[$k]['created_at'] = date('Y-m-d H:i', $v['created_at']);
        }
        return ['rows' => $rows, 'total' => $countQuery->count()];
    }

	public static function getDeliveries($id)
    {
        $query = DeliveryRecord::find()->where('status>0 AND cid=:cid', [':cid' => $id]);
        if (preg_match('/^[1-9]+[\d]*$/', $map)) {
            $query->andWhere('id=:id', [':id' => $map]);
        } elseif (is_array($map)) {
            $query->andWhere($map[0], $map[1]);
        } else {
            $query->andWhere($map);
        }
        return $query->asArray()->all();
    }

    public static function one($map, $toArray = 0)
    {
        $query = Contract::find()->where('status>0');
        if (preg_match('/^[1-9]+[\d]*$/', $map)) {
            $query->andWhere('id=:id', [':id' => $map]);
        } elseif (is_array($map)) {
            $query->andWhere($map[0], $map[1]);
        } else {
            $query->andWhere($map);
        }
        if ($toArray == 1) {
            $query->asArray();
        }
        return $query->one();
    }

    public static function set($force = 1)
    {
        if ($force == 1 || !Yii::$app->session->has('menus')) {
            $menus = Yarray::list_to_tree(self::getAllByAid());
            Yii::$app->session->set('menus', $menus);
            if (Yii::$app->session->has('menus')) {
                return $menus;
            }
            return false;
        }
        return Yii::$app->session->get('menus');
    }

    public static function remove($id)
    {
        if ($this->request->isAjax) {
            $model = self::one(['id=:id AND status<>-1', [':id' => $id]]);
            $model->scenario = Contract::SCENARIO_REMOVE;
            return $model->_save();
        }
    }

    public static function compltete($id)
    {
        if ($this->request->isAjax) {
            $model = self::one(['id=:id AND status=1', [':id' => $id]]);
            $model->scenario = Contract::SCENARIO_COMPLETE;
            return $model->_save();
        }
    }

    public static function getCustomerList()
    {
        $req = Yii::$app->request;
        $query = User::find();
        $query->select('u.id,u.realname,u.unit,u.mobile,u.level,u.pcc');
        $query->alias('u');
        $query->where('u.status=1 and u.level in (11, 12, 13, 14)');
        $query->andFilterWhere(['or', ['like', 'u.realname', $req->get('key')], ['like', 'u.unit', $req->get('key')], ['like', 'u.mobile', $req->get('key')]]);
        $countQuery = clone $query;
        $query->orderBy(['u.created_at' => SORT_DESC]);
        $rows = $query->offset($req->get('offset'))->limit($req->get('limit'))->asArray()->all();
        foreach ($rows as $k => $v) {
            switch ($v['level']) {
                case 11: $level_msg = '省'; break;
                case 12: $level_msg = '市'; break;
                case 13: $level_msg = '区县'; break;
                case 14: $level_msg = '乡镇'; break;
            }
            $rows[$k]['level_msg'] = $level_msg;
        }
        return ['rows' => $rows, 'total' => $countQuery->count()];
    }

}